package com.dh.spring.thread.runnable;

import com.dh.spring.thread.CustomTaskBlockQueue;
import com.dh.spring.thread.CustomThreadPool;
import com.dh.spring.util.LocalTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;

/**
 * 线程池内部线程执行单元Runnable
 *    线程池内部线程执行单元，用于从任务阻塞队列中循环获取任务执行
 * */
public class InternalRunnableTask implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(InternalRunnableTask.class);
    private CustomTaskBlockQueue customTaskBlockQueue;
    private CustomThreadPool customThreadPool;
    //TODO 线程执行单元运行状态 true停止 false运行
    private volatile boolean isStop = false;
    private static Object lock = new Object();

    public InternalRunnableTask(CustomThreadPool customThreadPool, CustomTaskBlockQueue customTaskBlockQueue) {
        this.customThreadPool = customThreadPool;
        this.customTaskBlockQueue = customTaskBlockQueue;
    }

    @Override
    public void run() {
        try {
            //TODO　循环从队列获取任务，如果能获取到则执行自定义任务处理，否则进行阻塞
            while(!isStop) {
                Runnable runnable = this.customTaskBlockQueue.takeRunnable();
                if (null != runnable) {
                    synchronized (lock) {
                        if(null != runnable) {
                            runnable.run();
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.info("[ " + LocalTime.formatDate(LocalDateTime.now()) + " ]"
                + " 当前线程 thread = " + Thread.currentThread().getName() + "中断，异常为：" + e.getMessage());
            e.printStackTrace();
        }
    }

    //TODO 线程执行单元停滞任务执行
    public void stop() {
        this.isStop = true;
    }
}
